<template>
  <div>
    <basic-dialog
      width="600px"
      title="选择可直送范围"
      :visible="visible"
      :handle-close="closeDialog"
      :handleOpened="getDeliveryRangeInfo"
      :handleOk="handleOk"
      ok-text="确认"
    >
      <!-- <div class="radioWrap">
        <el-radio-group v-model="directDeliveryRange">
          <el-radio :label="1">全国</el-radio>
          <el-radio :label="2">区域</el-radio>
        </el-radio-group>
      </div> -->
      <!-- v-if="directDeliveryRange == 2" -->
      <el-cascader-panel
        ref="rangePannel"
        :loading="rangeInfo.loading"
        v-model="rangeInfoValue"
        :props="rangeInfo.props"
        :options="rangeInfo.options"
        @change="handleNodeChange"
      ></el-cascader-panel>
    </basic-dialog>
  </div>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import {
  queryAllProvinceAndCityService
} from '@/api/sourcing/public';
const CITY_LENGTH = 390; // 市级联动长度
export default {
  // 厂家直送范围
  name: 'DeliveryRange',
  components: {
    BasicDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    provinceCityMap: {
      type: Object,
      default () {
        return {}
      }
    },
    directDeliveryRange: {
      type: Number,
      default: 1
    },
  },
  data () {
    return {
      rangeInfoValue: [],
      rangeInfo: {
        loading: false,
        rangeInfoValue: [],
        props: {
          multiple: true,
          label: 'name',
          value: 'code',
          id: 'id',
          leaf: 'id'
        },
        options: [],
        options2: [
          {
            id: '101',
            code: 101,
            name: '河北',
            children: [
              {
                id: '1001',
                code: 1001,
                name: '石家庄'
              }, {
                id: '1002',
                code: 1002,
                name: '廊坊'
              },
            ]
          }, {
            id: '102',
            code: 102,
            name: '河南',
            children: [
              {
                id: '1004',
                code: 1004,
                name: '郑州'
              }, {
                id: '1005',
                code: 1005,
                name: '洛阳'
              }
            ]
          }, {
            id: '103',
            code: 103,
            name: '山西',
            children: [
              {
                id: '1006',
                code: 1006,
                name: '太原'
              }, {
                id: '1007',
                code: 1007,
                name: '大同'
              }
            ]
          }, {
            id: '104',
            code: 104,
            name: '内蒙古',
            children: [
              {
                id: '1008',
                code: 1008,
                name: '呼和浩特'
              }, {
                id: '1009',
                code: 1009,
                name: '包头'
              }
            ]
          }
        ]
      },
    };
  },
  created () {
    this.getAreaTreeList()
  },
  watch: {
    provinceCityMap: {
      handler (val) {
        console.log(val)
        this.rangeInfoValue = [];
        if (this.directDeliveryRange == 1) {
          this.rangeInfoValue = this.transform1(this.rangeInfo.options[0].children);
        } else if (this.directDeliveryRange == 2) {
          this.rangeInfoValue = this.transform(this.provinceCityMap)
        }
      },
      deep: true
    }
  },
  methods: {
    // 获取直送范围信息
    getDeliveryRangeInfo () {
      /* this.$forceUpdate()
      this.$refs['rangePannel'].clearCheckedNodes(); */
    },
    // 获取全国所有市
    getAllCity (arr) {
      const allCityList = [];
      arr.forEach(item => {
        if (item.children) {
          item.children.forEach(item2 => {
            allCityList.push([item.code, item2.code]);
          })
        }
      });
      allCityList.forEach(item => {
        item.unshift(100)
      });
      return allCityList;
    },
    // 将全国 转化为 [[101, 1001],[101, 1002],[102, 1004],[102, 1005]]
    transform1 (arr) {
      const result = [];
      arr.forEach(item => {
        if (item.children) {
          item.children.forEach(item2 => {
            result.push([item.code, item2.code]);
          })
        }
      });
      result.forEach(item => {
        item.unshift(100)
      });
      return result;
    },
    // {101: [1001, 1002], 102: [1004, 1005]} 转化为 [[101, 1001],[101, 1002],[102, 1004],[102, 1005]]
    transform (obj) {
      let result = [];
      for (const key in obj) {
        const value = obj[key];
        for (const i in value) {
          result.push([Number(key), value[i]]);
        }
      }
      result.forEach(item => {
        item.unshift(100)
      });
      return result;
    },
    // 将[[101, 1001],[101, 1002],[102, 1004],[102, 1005]] 转化为 {101: [1001, 1002], 102: [1004, 1005]}
    transform2 (arr) {
      const result = {};
      arr.forEach(item => {
        if (item.length == 3) {
          item.shift(0);
        }
      });
      for (const [key, value] of arr) {
        if (result[key]) {
          result[key].push(value);
        } else {
          result[key] = [value];
        }
      }
      return result;
    },
    // 确认
    handleOk () {
      // 市集合
      const cityCodeList = this.rangeInfoValue.map(item => item[2] || item[1])
      // 市名称集合
      const cityNameList = this.$refs['rangePannel'].getCheckedNodes().filter(item => item.level == 3).map(item => item.label)
      let directDeliveryRange = '';
      let directDeliveryRangeStr = '';
      if (cityCodeList.length == this.getAllCity(this.rangeInfo.options[0].children).length) {
        directDeliveryRange = 1;
        directDeliveryRangeStr = '全国';
      } else {
        directDeliveryRange = 2;
        directDeliveryRangeStr = cityNameList.join(',');
      }
      this.closeDialog()
      this.$emit('confirm', {
        directDeliveryRange,
        directDeliveryRangeStr,
        cityCodeList,
        provinceCityMap: this.transform2(this.rangeInfoValue)
      })
    },
    // 获取省市
    async getAreaTreeList () {
      const res = await queryAllProvinceAndCityService(
        {},
        state => { this.loading = state }
      )
      if (res?.data) {
        this.rangeInfo.options = [{
          id: '100',
          code: 100,
          name: '全国',
          children: res?.data
        }]
      } else {
        this.rangeInfo.options = [{
          id: '100',
          code: 100,
          name: '全国',
          children: this.rangeInfo.options2
        }]
      }
    },
    // 选择末级节点
    handleNodeChange (val) {
      const selectNode = this.$refs['rangePannel'].getCheckedNodes();
      if (selectNode) {
      }
    },
    // 关闭弹框
    closeDialog () {
      // this.$refs['rangePannel'].clearCheckedNodes();
      this.$emit('update:visible', false)
    },
  }
};
</script>
<style lang="less" scoped>
  /deep/.el-scrollbar__wrap {
    overflow-x: hidden;
    height: 100%;
  }
  .radioWrap {
    margin-bottom: 10px;
  }
  /deep/ .el-cascader-menu {
    width: 33.3%;
    min-height: 200px;
  }
</style>
